package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-20
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult userlogin(LoginDto dto) {
        //用户名密码是否为空
        if(dto==null|| StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询用户
        LambdaQueryWrapper<AdUser> query=new LambdaQueryWrapper<>();
        query.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(query);
        if (one==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取用户的盐
        String salt = one.getSalt();
        //获得前端密码加盐加密后和数据库中的对比
        String pw=dto.getPassword()+salt;
        String pwmd= DigestUtils.md5DigestAsHex(pw.getBytes());
        if (!pwmd.equals(one.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //密码一致，使用JWT生成token,将id放入JWT的自定义声明中
        Map<String,Object> userMap=new HashMap<>();
        userMap.put("userId",one.getId());
        String token= AppJwtUtil.getToken(userMap);
        //返回前端
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        //隐藏敏感信息
        one.setPassword(null);
        one.setEmail(null);
        one.setPhone(null);
        map.put("user",one);
        return ResponseResult.okResult(map);
    }
}
